package com.itheima.mall.service.umsService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mall.mapper.umsMapper.UmsRoleResourceRelationMapper;
import com.itheima.pojo.ums.UmsRoleResourceRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsRoleResourceRelationApiImpl implements UmsRoleResourceRelationApi{
    @Autowired
    private UmsRoleResourceRelationMapper umsRoleResourceRelationMapper;

    /**
     * 给角色分配资源
     * @param resourceIds 资源ID数组
     * @param roleId 角色ID
     * @return
     */
    @Override
    public void allocResource(ArrayList<Long> resourceIds, Long roleId) {
        //删除原始分配资源
        LambdaQueryWrapper<UmsRoleResourceRelation> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsRoleResourceRelation::getRoleId,resourceIds);
        umsRoleResourceRelationMapper.delete(queryWrapper);
        //添加新分配资源
        for (Long resourceId : resourceIds) {
            UmsRoleResourceRelation umsRoleResourceRelation= new UmsRoleResourceRelation();
            umsRoleResourceRelation.setResourceId(resourceId);
            umsRoleResourceRelation.setRoleId(roleId);
            umsRoleResourceRelationMapper.insert(umsRoleResourceRelation);
        }

    }

    /**
     * 根据角色ID查询关联资源IDS数组
     * @param roleId 角色ID
     * @return
     */
    @Override
    public ArrayList<Long> getresourceIds(long roleId) {
        //条件查询
        LambdaQueryWrapper<UmsRoleResourceRelation> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsRoleResourceRelation::getRoleId,roleId);
        List<UmsRoleResourceRelation> umsRoleResourceRelations = umsRoleResourceRelationMapper.selectList(queryWrapper);
        //处理需要返回的数据
        ArrayList<Long> res =new ArrayList<>();
        umsRoleResourceRelations.forEach((umsRoleResourceRelation)->{
            res.add(umsRoleResourceRelation.getResourceId());
        });
        return res;
    }
}
